package com.sgb.kjwl.viewmodel.self.publish;

import androidx.databinding.ObservableField;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.jicai.entity.FilterEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.link.entity.PublicTypeEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddMachineOutEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseMachineActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LeaseMachineModel extends BaseViewModel {
    public ObservableField<AddMachineOutEntity> addMachineOutEntity = new ObservableField<>(new AddMachineOutEntity());
    private final LeaseMachineActivity activity;
    private final SelfRepertory repertory;

    public LeaseMachineModel(LeaseMachineActivity activity, SelfRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    //新增机械出租发布
    public void addMachineOutModel(String id) {
        addMachineOutEntity.get().setId(id);
        APIManager.getInstance().getLeaseAPI().addOrUpdateMachine(addMachineOutEntity.get()).enqueue(new ICallBack<BaseEntity>(true) {
            @Override
            public void onSuccess(BaseEntity data) {
                EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_LEASE_PUBLISH_FILTER));
                activity.showSuccess();
                activity.finish();
            }
        });
    }

    //获取机械出租详情
    public void getMachineOutDetailModel(String id) {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getPublishMachineOutDetail(id).enqueue(
                new Callback<BaseEntity<AddMachineOutEntity>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<AddMachineOutEntity>> call, Response<BaseEntity<AddMachineOutEntity>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) return;
                        if (response.body().getData() != null && response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            activity.showEditView(response.body().getData());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<AddMachineOutEntity>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                }
        );
    }

    public void getMachineTypeModel() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.getMachineOutType()
                .subscribe(new Consumer<BaseEntity<List<PublicTypeEntity<List<PublicTypeEntity>>>>>() {
                    @Override
                    public void accept(BaseEntity<List<PublicTypeEntity<List<PublicTypeEntity>>>> listBaseEntity) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        activity.getMachineTypeSucc(listBaseEntity.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

//    //获取机械型号和属性(废弃)
//    public void getMachineDictModel(String firstCategory, String secondCategory) {
//        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
//        repertory.getMachineDict(firstCategory, secondCategory)
//                .subscribe(new Consumer<BaseEntity<List<FilterEntity<List<FilterEntity>>>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<FilterEntity<List<FilterEntity>>>> listBaseEntity) throws Exception {
//                        DialogHelper.dismissProgressDialog();
//                        activity.getMachineArrtSucc(listBaseEntity.getData());
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        DialogHelper.dismissProgressDialog();
//                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
//                    }
//                });
//    }

    //获取机械属性
    public void getMachineDictModel(String firstCategoryNo, String secondCategoryNo) {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("categoryType", 1);//1为机械
        map.put("firstCategoryNo", firstCategoryNo);
        map.put("secondCategoryNo", secondCategoryNo);
        APIManager.getInstance().getLeaseAPI().getAttributeList(map).enqueue(
                new Callback<BaseEntity<List<FilterEntity<List<FilterEntity>>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<FilterEntity<List<FilterEntity>>>>> call, Response<BaseEntity<List<FilterEntity<List<FilterEntity>>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) return;
                        activity.getMachineArrtSucc(response.body().getData());
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<FilterEntity<List<FilterEntity>>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                }
        );
    }

    public void getCustomerOrgDatas() {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getMachineAPI().getCustomerOrg().enqueue(
                new Callback<BaseEntity<List<ServiceEntity>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<ServiceEntity>>> call, Response<BaseEntity<List<ServiceEntity>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) return;
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            activity.getCustomerOrgDataS(response.body().getData());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<ServiceEntity>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                }
        );
    }

//    //获取价格单位
//    public void getMachinePriceModel() {
//        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
//        repertory.getMachinePrice()
//                .subscribe(new Consumer<BaseEntity<List<DictEntity>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<DictEntity>> listBaseEntity) throws Exception {
//                        DialogHelper.dismissProgressDialog();
//                        activity.showUnitPop(listBaseEntity.getData());
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        DialogHelper.dismissProgressDialog();
//                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
//                    }
//                });
//    }


    //获取价格单位
    public void getTimeUnitModel() {
        APIManager.getInstance().getMachineAPI().getMachineTimeUnit().enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> response) {
                if (response.body() == null || response.body().getState() == null) return;
                activity.setTimeList(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Throwable t) {
            }
        });
    }

//    //获取价格单位
//    public void getMachinePriceModel() {
//        APIManager.getInstance().getMachineAPI().getMachinePrice().enqueue(new Callback<BaseEntity<List<DictEntity>>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<List<DictEntity>>> call, Response<BaseEntity<List<DictEntity>>> response) {
//                DialogHelper.dismissProgressDialog();
//                if (null != response.body()) {
//                    activity.setDictEntityList(response.body().getData());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<List<DictEntity>>> call, Throwable t) {
//                DialogHelper.dismissProgressDialog();
//
//            }
//        });
//    }

    //获取税率列表
    public void getLeaseRate() {
        APIManager.getInstance().getLeaseAPI().getLeaseRate().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showRate(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
            }
        });
    }


    public void getAddressModel() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) return;
                if (response.body().getCode().equals("200"))
                    activity.showAddressPop(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    //上传多图片
    /*public void uploadMutiFileModel(List<File> fileList, int type, int isfile, List<String> netUrls) {
        DialogHelper.showProgressDialog(activity, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.uploadMutiFile(fileList)
                .subscribe(new Consumer<BaseEntity<List<String>>>() {
                    @Override
                    public void accept(BaseEntity<List<String>> baseEntity) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        activity.uploadImgSuccess(baseEntity.getData(), type, isfile, netUrls);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }*/

    //上传多图片
    public void uploadMutiFileModel(File file, int type, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + activity.imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadRefresh(response.body().getData().toString(), type);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    //获取经纬度信息
    public void getLocationLL(String provinceNo, String cityNo, String districtNo) {
        DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(repertory.getAreaCode(), provinceNo, cityNo, districtNo).enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getLocationLL(response.body().getData());
                } else {
                    MToast.showToast(activity.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity.getActivity(), t.getMessage());
            }
        });

    }

    //获取申请部门
    public void getDepartment() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getUserDepartmentImg().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showDepartment(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //判断公司是否有审批
    public void haveApprovalOrNot(String companyNo, String type) {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().haveApprovalOrNot(companyNo, type).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    try {//接口返回数据不标准,只能自行转换
                        JSONObject jsonObject = new JSONObject(response.body().getData().toString());
                        String str = jsonObject.getString("data");
                        //0无审批流 1 有审批流
                        activity.showPublishTip("1".equals(str));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        MToast.showToast(activity, "服务异常");
                    }

                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
